<template>
  <div class="app-container">
    <!-- <div class="header_title_box">
      <h2>调拨单管理</h2>
    </div> -->
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch">
      <div class="mb10">
        <el-button size="mini" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </form-selections>
    <div style="margin-top:20px;" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'allotOrder@save'" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="toAddAllotOrder">创建调拨单</el-button>
        <el-button v-action="'allotOrder@SubmitAudit'" size="small" type="primary" @click="submitAudit">提交审核</el-button>
        <el-button v-action="'allotOrder@changeAuditStatus'" size="small" type="primary" @click="showAuditDialog(1)">调出审核</el-button>
        <el-button v-action="'allotOrder@changeAuditStatus'" size="small" type="primary" @click="showAuditDialog(2)">调入审核</el-button>
        <el-button v-action="'allotOrder@batchDelete'" size="small" type="danger" @click="dels(0)">批量删除</el-button>
        <el-button v-action="'allotOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        <el-button v-action="'allotOrder@importOrder'" size="small" type="primary" :loading="exportLoading" @click="formVisibleFile=true">导入调拨单</el-button>
      </div>
    </div>
    <div v-loading="loading">
      <el-table :data="data" border fit :row-class-name="tableRowClassName" :max-height="screenHeigh" @selection-change="handleSelectMulti">
        <el-table-column type="selection" width="51" align="center" />
        <el-table-column label="操作" align="center" width="135" fixed>
          <template slot-scope="scope">
            <span v-if="![2, 3].includes(scope.row.audit_status)" v-action="'allotOrder@update'" class="edit_style" style="margin: 0;" @click="handleUpdate(scope.row)">编辑</span>
            <span v-if="![2, 3].includes(scope.row.audit_status)" v-action="'allotOrder@batchDelete'" class="delete_style" style="margin: 0;" @click="dels(scope.row.id)">删除</span>
            <span v-action="'allotOrder@read'" class="edit_style" style="margin: 0;" @click="toInfo(scope.row.id)">详情</span>
          </template>
        </el-table-column>
        <el-table-column label="调出仓" prop="transfer_out_warehouse" align="center" width="238" />
        <el-table-column label="调入仓" prop="transfer_in_warehouse" align="center" width="220" />
        <el-table-column label="所属实体仓" prop="entity_warehouse" align="center" width="202" />
        <el-table-column label="审核状态" prop="audit_status" align="center" width="124">
          <template slot-scope="scope">
            <span>{{ statusMap[scope.row.audit_status] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核原因" prop="audit_status" align="center" width="144" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.audit_notes || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="系统SKU|商品名称|数量" width="400px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.products" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }}<b>|</b>{{ item.number }} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="配件SKU|配件名称|数量" width="300px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.parts" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }}<b>|</b>{{ item.number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="created_by_name" align="center" width="112" />
        <el-table-column label="创建时间" prop="created_at" align="center" width="174" />
        <el-table-column label="修改人" prop="updated_by_name" align="center" width="112" />
        <el-table-column label="修改时间" prop="updated_at" align="center" width="174" />
      </el-table>
      <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <audit-dialog ref="auditDialog" :base-fields="baseFields" :number-desc="numberDesc" :change-audit-url="changeAuditUrl" :show-parts="true" :info-url="infoUrl" @submit="auditHandler" />
    <warehouse-order-info-dialog ref="infoDialog" :base-fields="baseFields" :number-desc="numberDesc" />
    <!--下载字段选择-->
    <DownModul :url="exportUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="仓库调拨单导出字段选择" :options-modul="optionsModul" />
    <ImportDialog url="/allot-order-import" title="导入调拨单" :form-visible.sync="formVisibleFile" @download="downLoad" @handleRefresh="handleRefresh" />
  </div>
</template>

<script>
import formOperate from '../../../layout/mixin/formOperate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import auditDialog from '../components/auditDialog'
import warehouseOrderInfoDialog from '../components/warehouseOrderInfoDialog'
import cacheList from '@/layout/mixin/cacheList'
import DownModul from '@/components/DownModul/index.vue'
import ImportDialog from '@/components/importDialog/index.vue'
import { downloadStream } from '@/utils/index'
export default {
  name: 'AllotOrder',
  directives: {
    action
  },
  components: {
    auditDialog,
    warehouseOrderInfoDialog,
    DownModul,
    ImportDialog
  },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 355,
      formVisibleFile: false,
      componentName: 'AllotOrder',
      url: '/allot-order',
      formItems: [
        {
          label: '仓库名称',
          key: 'warehouse_name',
          type: 'input',
          placeholder: '请输入仓库名称'
        },
        {
          label: '商品SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入商品SKU'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        },
        {
          label: '日期',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      queryParam: {
        warehouse_name: '',
        audit_status: '',
        page: 1,
        limit: 10
      },
      statusList: [
        {
          id: 0,
          name: '待提交'
        },
        {
          id: 1,
          name: '待审核'
        },
        {
          id: 2,
          name: '调出审核通过'
        },
        {
          id: 3,
          name: '调入审核通过'
        },
        {
          id: -1,
          name: '调出审核驳回'
        },
        {
          id: -2,
          name: '调入审核驳回'
        }
      ], // 审核状态list
      statusMap: {
        0: '待提交',
        1: '待审核',
        2: '调出审核通过',
        3: '调入审核通过',
        '-1': '调出审核驳回',
        '-2': '调入审核驳回'
      },
      baseFields: [
        {
          id: 1,
          label: '实体仓',
          prop: 'entity_warehouse'
        },
        {
          id: 2,
          label: '调出虚拟仓',
          prop: 'transfer_out_warehouse'
        },
        {
          id: 3,
          label: '调入虚拟仓',
          prop: 'transfer_in_warehouse'
        },
        {
          id: 4,
          label: '调拨原因',
          prop: 'notes'
        }
      ],
      numberDesc: {
        label: '调拨数量',
        prop: 'number'
      },
      changeAuditUrl: '/allot-order/change-audit-status',
      infoUrl: '/allot-order',
      exportUrl: '/allot-order-export',
      cachePaths: [
        '/storage/allotOrder/'
      ],
      optionsModul: [
        {
          key: 'entity_warehouse',
          label: '实体仓'
        },
        {
          key: 'transfer_in_warehouse',
          label: '调入虚拟仓'
        },
        {
          key: 'transfer_out_warehouse',
          label: '调出虚拟仓'
        },
        {
          key: 'audit_status_text',
          label: '审核状态'
        },
        {
          key: 'goods_name',
          label: '商品名称'
        },
        {
          key: 'goods_code',
          label: '商品SKU'
        },
        {
          key: 'number',
          label: '商品数量'
        },
        {
          key: 'created_by_name',
          label: '创建人'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ]
    }
  },
  activated() {
    this.getList()
  },
  methods: {
    beforeSearch() {
      const vm = this
      vm.queryParam.start_at = ''
      vm.queryParam.end_at = ''
      // 生成日期转化
      if (vm.queryParam.dateCreat && vm.queryParam.dateCreat.length > 0) {
        vm.queryParam.start_at = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at = vm.queryParam.dateCreat[1]
      }
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/allot-order-import-templage', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '调拨单模板.xlsx')
        })
    },
    // 导出
    handleExport() {
      const vm = this
      // const { warehouse_name, audit_status } = vm.queryParam
      // const params = { warehouse_name, audit_status }
      //   vm.handleExportxlsx(vm.exportUrl, { params })
      vm.downLoadParams = vm.queryParam
      vm.formVisibleDown = true
    },
    // 去详情
    toInfo(id) {
      const vm = this
      vm.$router.push({
        path: `/storage/allotOrder/info/${id}`,
        query: { title: '调拨单详情' }
      })
    },
    // 添加
    toAddAllotOrder() {
      const vm = this
      window.localStorage.removeItem('allotOrder')
      vm.$router.push({ path: '/storage/allotOrder/add' })
    },
    // 批量删除
    dels(id) {
      const vm = this
      let ids = []
      if (id) {
        ids.push(id)
      } else {
        ids = vm.selectedIds
      }
      vm.$confirm(`确定${id ? '' : '批量'}删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http.post('/allot-order/batch-delete', { ids }).then((res) => {
          vm.$message.success('删除成功')
          vm.getList()
        })
      })
    },
    // 修改
    handleUpdate(row) {
      const vm = this
      window.localStorage.removeItem('allotOrder')
      vm.$router.push({
        path: `/storage/allotOrder/add/${row.id}`,
        query: { title: '编辑调拨单' }
      })
    },
    // 提交审核
    submitAudit() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      // 判断列表是否都是 待提交状态
      const isEveryToSubmit = vm.data
        .filter((e) => vm.selectedIds.includes(e.id))
        .every((e) => [0, -1, -2].includes(e.audit_status))
      if (isEveryToSubmit) {
        vm.$confirm(`确定提交审核吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.$http
            .post('/allot-order/submit-audit', { ids: vm.selectedIds })
            .then((res) => {
              vm.$message.success('提交审核成功')
              vm.getList()
            })
        })
      } else {
        vm.$message.error('选择数据须都是待提交或审核驳回状态')
      }
    },
    // 显示提交审核弹窗 {type} 1 调出 2 调入
    showAuditDialog(type) {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      if (vm.selectedIds.length > 1) {
        vm.$message.error('请至多选择一条数据')
        return
      }
      const firstId = vm.selectedIds[0]
      const first = vm.data.find((e) => e.id === firstId)
      let auditStatus = []
      if (type === 1) {
        // 调出审核
        if (first.audit_status !== 1) {
          vm.$message.error('选择数据必须是待审核状态')
          return
        }
        auditStatus = [
          {
            label: 2,
            name: '调出审核通过'
          },
          {
            label: -1,
            name: '调出审核驳回'
          }
        ]
      } else {
        // 调入审核
        if (first.audit_status !== 2) {
          vm.$message.error('选择数据必须是调出审核通过状态')
          return
        }
        auditStatus = [
          {
            label: 3,
            name: '调入审核通过'
          },
          {
            label: -2,
            name: '调入审核驳回'
          }
        ]
      }
      vm.$refs['auditDialog'].show({ id: firstId, auditStatus })
    },
    // 审核 handler
    auditHandler() {
      const vm = this
      vm.getList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
